package com.woyao;

import android.Manifest;
import android.app.Application;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.squareup.picasso.Picasso;
import com.woyao.core.FileUtil;
import com.woyao.core.model.GetChildOccupationResponse;
import com.woyao.core.model.KeyValue;
import com.woyao.core.model.KeyValueList;
import com.woyao.core.model.ProfileResponse;
import com.woyao.core.model.User;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;
import com.woyao.core.util.StringUtil;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;

//import com.woyao.core.AreaPopUp;

public class AccountActivity extends AppCompatActivity {
    private User user = new User();

    private TextView name;
    private TextView addr;
    private TextView occupation;
    private TextView buzz;
    private TextView intro;

    private TextView phoneTxt;
    private TextView wechatTxt;
    private TextView emailTxt;
    private TextView officeTxt;
    private TextView categoryTxt;

    private  TextView birthdayTxt;
    private  TextView eduTxt;
    private RadioGroup sexRG;
    private ContentResolver cr;

    private LinearLayout introArea;

    private CircleImageView avatar;
    Button nextbtnRegister ;
    ProgressDialog progressDialog;

    private ArrayList<KeyValue> occupations  = new ArrayList<KeyValue>();
    private String from = "";

    private Integer NAME_CODE = 50;
    private Integer AVART_CODE = 100;
    private Integer INTRO_CODE = 300;
    private Integer LOCATION_CODE = 700;


    private Integer PHONE_CODE = 800;
    private Integer WECHAT_CODE = 900;
    private Integer EMAIL_CODE = 1000;
    private Integer OFFICE_CODE = 1100;

    private Integer CATEGORY_CODE = 1200;

    private Integer BUSINESS_CODE = 600;

    private String[] education = {"小学","初中","中专","高中", "专科","本科","硕士","博士" };

    private ProgressBar progress;

    private Button viewBtn;
    private boolean loading = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout

        progress = (ProgressBar)  findViewById(R.id.account_uploading);

        introArea = (LinearLayout) findViewById(R.id.account_intro_area);

        eduTxt = (TextView) findViewById(R.id.id_edu);

        eduTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                modifyEdu();
            }
        });

        sexRG = (RadioGroup) findViewById(R.id.id_sex);

        sexRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (!loading){
                    if (i== R.id.id_sex_male){
                        user.setSex( 1 );
                    }
                    if (i== R.id.id_sex_female){
                        user.setSex( 2 );
                    }
                    Common.setProfileAttr("sex", user.getSex() + "");
                }
            }
        });

        birthdayTxt = (TextView) findViewById(R.id.id_birthday);

        birthdayTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                modifyBirthday();
            }
        });

        viewBtn = (Button)findViewById(R.id.view_self) ;

        viewBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("id", userId);
                intent.setClass(AccountActivity.this, PersonViewActivity.class);
                startActivity(intent);
            }
        });

        name = (TextView)findViewById(R.id.id_username);

        name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("type","displayname");
                intent.putExtra( "content", user.getDisplayname() );
                intent.setClass(AccountActivity.this,  InputActivity.class);
                startActivityForResult(intent,NAME_CODE);
            }
        });

        addr = (TextView)findViewById(R.id.id_addr);
        addr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(AccountActivity.this, ConfirmLocation.class);
                startActivityForResult(intent, LOCATION_CODE);
//                popUp.showPopupWindow();
            }
        });

        occupation = (TextView)findViewById(R.id.id_occupation);
        occupation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                confirmOccupation( );
            }
        });

        buzz = (TextView)findViewById(R.id.id_buzz);
        buzz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(AccountActivity.this, ConfirmBusiness.class);
                startActivityForResult(intent, BUSINESS_CODE);
//                popUp.showPopupWindow();
            }
        });

        categoryTxt = (TextView)findViewById(R.id.id_category);
        categoryTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                KeyValueList kvl = new KeyValueList();
                kvl.setContent( user.getCategory_list() );
                intent.putExtra("category_list", kvl  );
                intent.setClass(AccountActivity.this, FilterCategory.class);
                startActivityForResult(intent, CATEGORY_CODE);
//                popUp.showPopupWindow();
            }
        });


        intro = (TextView)findViewById(R.id.id_intro);
        intro.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("type","intro");
                intent.putExtra( "content", user.getIntro() );
                intent.setClass(AccountActivity.this,  InputActivity.class);
                startActivityForResult(intent,INTRO_CODE);
            }
        });



        avatar = (CircleImageView)findViewById(R.id.id_avatar);
        avatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               addMedia();
            }
        });


        phoneTxt = (TextView)findViewById(R.id.id_phone);

        phoneTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("type","phone");
                intent.putExtra( "content", user.getPhone() );
                intent.setClass(AccountActivity.this,  InputActivity.class);
                startActivityForResult(intent,PHONE_CODE);
            }
        });

        wechatTxt = (TextView)findViewById(R.id.id_wechat);

        wechatTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("type","wechat");
                intent.putExtra( "content", user.getWechat() );
                intent.setClass(AccountActivity.this,  InputActivity.class);
                startActivityForResult(intent,WECHAT_CODE);
            }
        });

        emailTxt = (TextView)findViewById(R.id.id_email);

        emailTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("type","email");
                intent.putExtra( "content", user.getEmail() );
                intent.setClass(AccountActivity.this,  InputActivity.class);
                startActivityForResult(intent,EMAIL_CODE);
            }
        });

        officeTxt = (TextView)findViewById(R.id.id_office);

        officeTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("type","office");
                intent.putExtra( "content", user.getOffice() );
                intent.setClass(AccountActivity.this,  InputActivity.class);
                startActivityForResult(intent,OFFICE_CODE);
            }
        });


        nextbtnRegister = (Button) findViewById(R.id.register_btn1);

        nextbtnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finishAccount();

            }
        });

        final Button nextbtn = (Button) findViewById(R.id.add_next);

        nextbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finishAccount();

            }
        });



        Intent intent = getIntent();
        from = intent.getStringExtra( "from");
        if (from == null){
            from = "";
        }
        this.setTitle("请填写个人信息");
        loadData();
        loadOccupation();



    }

    private void addMedia(){


        if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){ //权限没有被授予
            /**3.申请授权
             * @param
             *  @param activity The target activity.（Activity|Fragment、）
             * @param permissions The requested permissions.（权限字符串数组）
             * @param requestCode Application specific request code to match with a result（int型申请码）
             *    reported to {@link OnRequestPermissionsResultCallback#onRequestPermissionsResult(
             *    int, String[], int[])}.
             * */
            Dialog alertDialog = new AlertDialog.Builder(this).
                    setTitle("信息").
                    setMessage( "为上传头像图片，请授权访问设备的图片资料").
                    setIcon(R.drawable.ic_launcher).
                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(AccountActivity.this,
                                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                    520);
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            }).create();
            alertDialog.show();


        }else{//权限被授予
            try {
                // Open default camera
                // Intent intent = new Intent(Intent.ACTION_PICK);   , MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                Intent intent = new Intent(Intent.ACTION_PICK);  
                intent.setType("image/");

                // start the image capture Intent
                startActivityForResult(intent, AVART_CODE);

            }catch(Exception e){
                e.printStackTrace();
            }
        }

    }

    private int eduChoice = 0;
    private void modifyEdu(){
        AlertDialog.Builder singleChoiceDialog =
                new AlertDialog.Builder(AccountActivity.this);
        singleChoiceDialog.setTitle("选择学历");
        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(education, 0,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        eduChoice = which;
                    }
                });
        singleChoiceDialog.setPositiveButton("确 定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (eduChoice != -1) {
                            if (eduChoice < education.length  ) {
                                user.setEdu( education[eduChoice]);
                                eduTxt.setText( user.getEdu());
                                eduTxt.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark));
                                Common.setProfileAttr("edu", user.getEdu());
                            }
                        }
                    }
                });

        singleChoiceDialog.show();
    }

    private void modifyBirthday(){

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");
        Date dt = new Date();

        try {
            if (user.getBirthday().equals("" )){
                dt = formatter.parse("2000-06-15");
            }else{
                dt = formatter.parse(user.getBirthday());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        calendar.setTime(dt);

        int year=calendar.get(Calendar.YEAR);
        int month=calendar.get(Calendar.MONTH);
        int day=calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog begindatePicker = new DatePickerDialog(AccountActivity.this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {

                int day = datePicker.getDayOfMonth();
                int month = datePicker.getMonth() ;
                int year =  datePicker.getYear();

                Calendar calendar = Calendar.getInstance();
                calendar.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                calendar.set(year, month, day);

                SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");
                String thedatestr = formatter.format(calendar.getTime());
                user.setBirthday( thedatestr );
                birthdayTxt.setText( user.getBirthday());

                birthdayTxt.setTextColor(getResources().getColor(R.color.colorPrimaryDark));

                Common.setProfileAttr("birthday",user.getBirthday());

            }
        }, year, month, day);
        begindatePicker.show();
    }
    private Integer yourChoice = 0 ;
    private void confirmOccupation( ){


        yourChoice = 0 ;
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < occupations.size(); i++) {
            KeyValue ds = occupations.get(i);
            list.add(ds.getName());
        }


        final String[] items =  (String[])list.toArray(new String[0]);

        AlertDialog.Builder singleChoiceDialog =
                new AlertDialog.Builder(AccountActivity.this);
        singleChoiceDialog.setTitle("选择职业");
        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, 0,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        yourChoice = which;
                    }
                });
        singleChoiceDialog.setPositiveButton("确 定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (yourChoice != -1) {
                            if (yourChoice < items.length  ) {
                                user.setOccupation( occupations.get(yourChoice).getNo());
                                user.setOccupation_name( occupations.get(yourChoice).getName());

                                occupation.setText(user.getOccupation_name());
                                occupation.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark));
                                Common.setProfileAttr("occupation", user.getOccupation());
                            }
                        }
                    }
                });

        singleChoiceDialog.show();

    }

    private void loadOccupation(){

        AsyncTask<Void, Void, GetChildOccupationResponse> task =new AsyncTask<Void, Void, GetChildOccupationResponse>() {
            @Override
            protected GetChildOccupationResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetChildOccupationResponse> responseCall = svc.getChildOccupation(userId,"");
                try {
                    GetChildOccupationResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetChildOccupationResponse response) {
                if (response != null && response.getContent() !=null){
                    occupations = response.getContent();

                }

            }
            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void)null);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == 520)
        {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                try {
                    // Open default camera
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/");

                    // start the image capture Intent
                    startActivityForResult(intent, AVART_CODE);

                }catch(Exception e){
                    e.printStackTrace();
                }
            } else
            {
                Toast.makeText(AccountActivity.this, "权限被拒绝，图片不能正常上传", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    private void finishAccount(){
        if( user.getDisplayname().equals("")) {

            Dialog alertDialog = new AlertDialog.Builder(AccountActivity.this).
                    setTitle("信息").
                    setMessage("请填写称呼").
                    setIcon(R.drawable.ic_launcher).
                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent();
                            intent.putExtra("type","displayname");
                            intent.putExtra( "content", user.getDisplayname() );
                            intent.setClass(AccountActivity.this,  InputActivity.class);
                            startActivityForResult(intent,NAME_CODE);

                        }
                    }).
                    create();
            alertDialog.show();

            return;
        }

        if( user.getProvince() == 0) {

            Dialog alertDialog = new AlertDialog.Builder(AccountActivity.this).
                    setTitle("信息").
                    setMessage("请选择所在地区").
                    setIcon(R.drawable.ic_launcher).
                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent();
                            intent.setClass(AccountActivity.this, ConfirmLocation.class);
                            startActivityForResult(intent, LOCATION_CODE);

                        }
                    }).
                    create();
            alertDialog.show();
            return;
        }

        if( user.getOccupation().equals("")) {

            Dialog alertDialog = new AlertDialog.Builder(AccountActivity.this).
                    setTitle("信息").
                    setMessage("请选择职业").
                    setIcon(R.drawable.ic_launcher).
                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                           confirmOccupation();
                        }
                    }).
                    create();
            alertDialog.show();
            return;
        }

//        if (user.getSex() == 0){
//            Common.alert(AccountActivity.this,"请选择性别");
//            return;
//        }
//        if( user.getBusiness().equals("")) {
//
//            Dialog alertDialog = new AlertDialog.Builder(AccountActivity.this).
//                    setTitle("信息").
//                    setMessage("请选择所在行业").
//                    setIcon(R.drawable.ic_launcher).
//                    setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            Intent intent = new Intent();
//                            intent.setClass(AccountActivity.this, ConfirmBusiness.class);
//                            startActivityForResult(intent, BUSINESS_CODE);
//
//                        }
//                    }).
//                    create();
//            alertDialog.show();
//            return;
//        }

//        if( user.getCategory().equals("")) {
//
//            Dialog alertDialog = new AlertDialog.Builder(AccountActivity.this).
//                    setTitle("信息").
//                    setMessage("请选择合作领域").
//                    setIcon(R.drawable.ic_launcher).
//                    setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            Intent intent = new Intent();
//                            KeyValueList kvl = new KeyValueList();
//                            kvl.setContent( user.getCategory_list() );
//                            intent.putExtra("category_list", kvl  );
//                            intent.setClass(AccountActivity.this, FilterCategory.class);
//                            startActivityForResult(intent, CATEGORY_CODE);
//
//                        }
//                    }).
//                    create();
//            alertDialog.show();
//            return;
//        }


        Application application = getApplication();

        SharedPreferences shared = application.getSharedPreferences("login", MODE_PRIVATE);

        SharedPreferences.Editor editor = shared.edit();
        editor.putString("displayname", user.getDisplayname());
        editor.putString("location", user.getLocation());

        editor.commit();


        Intent intent = new Intent();
        intent.putExtra("displayname",user.getDisplayname());
        setResult(666, intent);

        finish();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        intent.putExtra("displayname",user.getDisplayname());
        setResult(0, intent);
        finish();
        return true;
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == NAME_CODE && resultCode ==666 ) {    // 称呼
            CharSequence con = data.getCharSequenceExtra("content");
            if (con == null) return;
            name.setText(con);
            name.setTextColor( ContextCompat.getColor(this, R.color.colorTextPrimary) );
            user.setDisplayname( con.toString());
            WoyaoooApplication.displayname = con.toString();
            name.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark) );
            Common.setProfileAttr("displayname", con.toString());
        }else if (requestCode == BUSINESS_CODE && resultCode == 666) {
            KeyValueList result = (KeyValueList) data.getExtras().get("result");
            user.setBusiness_name(Common.KeyValueToNames(result.getContent()));
            user.setBusiness(Common.KeyValueToNos(result.getContent()));
            buzz.setText(user.getBusiness_name());
            buzz.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark));
            Common.setProfileAttr("business", user.getBusiness());
        } else if (requestCode == LOCATION_CODE && resultCode == 666) {
            String locationNo = data.getStringExtra("no");
            String locationName = data.getStringExtra("name");
            user.setLocation(locationName);
            user.setProvince( Integer.parseInt( locationNo));
            addr.setText(user.getLocation());
            addr.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark));
            Common.setProfileAttr("location", locationNo);
        }  if  (requestCode == CATEGORY_CODE && resultCode ==666){
            KeyValueList thelist = (KeyValueList) data.getExtras().get("result");
            user.setCategory_list( thelist.getContent());
            user.setCategory_name(  Common.KeyValueToNames( thelist.getContent()) );
            user.setCategory(  Common.KeyValueToNos( thelist.getContent()) );
            categoryTxt.setText( user.getCategory_name() );
            categoryTxt.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark));
            Common.setProfileAttr("category", user.getCategory());
        } else if(requestCode == INTRO_CODE  && resultCode == 666 ) {
            CharSequence con = data.getCharSequenceExtra("content");
            if (con == null) return;
            intro.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark) );
            intro.setText( con.toString());
            Common.setProfileAttr("intro", con.toString());
        }else if(requestCode == PHONE_CODE  && resultCode == 666 ) {
            CharSequence con = data.getCharSequenceExtra("content");
            if (con == null) return;
            user.setPhone(con.toString());
            phoneTxt.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark) );
            phoneTxt.setText( user.getPhone());
            Common.setProfileAttr("phone", user.getPhone());
        }else if(requestCode == WECHAT_CODE  && resultCode == 666 ) {
            CharSequence con = data.getCharSequenceExtra("content");
            if (con == null) return;
            user.setWechat(con.toString());
            wechatTxt.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark) );
            wechatTxt.setText( user.getWechat());
            Common.setProfileAttr("wechat", user.getWechat());
        }else if(requestCode == EMAIL_CODE  && resultCode == 666 ) {
            CharSequence con = data.getCharSequenceExtra("content");
            if (con == null) return;
            user.setEmail(con.toString());
            emailTxt.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark) );
            emailTxt.setText( user.getEmail());
            Common.setProfileAttr("email", user.getEmail());
        }else if(requestCode == OFFICE_CODE  && resultCode == 666 ) {
            CharSequence con = data.getCharSequenceExtra("content");
            if (con == null) return;
            user.setOffice(con.toString());
            officeTxt.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark) );
            officeTxt.setText( user.getOffice());
            Common.setProfileAttr("office", user.getOffice());
        }else if (requestCode == AVART_CODE && resultCode == RESULT_OK) {
            try{
//                Uri selectedImage = data.getData();
//
//                Bitmap preview =null;
//                try {
//                    preview =  FileUtil.decodeUri(selectedImage, AccountActivity.this);
//                } catch (FileNotFoundException e) {
//                    e.printStackTrace();
//                }
//                String localpicpath = Common.getPath(AccountActivity.this,selectedImage);
//                uploadAvatar(localpicpath,preview);
                Uri selectedImageUri = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };

                Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
                if (cursor != null) {
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    Bitmap preview = BitmapFactory.decodeFile(picturePath);
                    uploadAvatar(picturePath,preview);
                }


            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }



    public void showFailure() {//自定义方法名tt
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progress.setVisibility(View.GONE);
                progressDialog.dismiss();
                Common.showSnack(AccountActivity.this,avatar,"上传失败");
            }
        });
    }


    public void showAvatar(final Bitmap preview) {//自定义方法名tt
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progress.setVisibility(View.GONE);
                progressDialog.dismiss();
                avatar.setImageBitmap(preview);
                Common.showSnack(AccountActivity.this,avatar,"上传成功");
            }
        });
    }

    private void uploadAvatar(  String localpicpath, final Bitmap preview){
        progressDialog = new ProgressDialog(AccountActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("图片上传中...");
        progressDialog.show();
        final String filename =  FileUtil.getAvatarObjectKey();
        OSS oss = FileUtil.getOss(getApplicationContext());
        PutObjectRequest put = new PutObjectRequest(FileUtil.bucketName, filename, localpicpath);

// 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                progress.setVisibility(View.VISIBLE);
                progress.setProgress(  Math.round( 100* currentSize / totalSize)  );
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Common.setProfileAttr("snailview", "aliyun"+ filename);
                showAvatar(preview);

//                Toast.makeText(AccountActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                showFailure();
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常

                }

            }
        });

    }






    private void loadData(){

        progressDialog = new ProgressDialog(AccountActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("加载信息···");
        progressDialog.show();
        AsyncTask<Void,Void,ProfileResponse> loadTask =
                new AsyncTask<Void, Void, ProfileResponse>() {
                    @Override
                    protected ProfileResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<ProfileResponse> responseCall = svc.getProfile(userId,"android",Common.getCurrentVersion(AccountActivity.this));
                        try {
                            ProfileResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                    @Override
                    protected void onPostExecute(final ProfileResponse response) {
                        progressDialog.dismiss();
                        if(response != null && response.isSuccess()){
                            renderAccount(response);
                        }
                    }
                };
        loadTask.execute((Void)null);
    }



    private void renderAccount(ProfileResponse response){
        loading = true;
        this.user = response.getContent();

        if (!user.getBirthday().equals("" )){
            birthdayTxt.setText( user.getBirthday());
            birthdayTxt.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark) );
        }

        if (!user.getEdu().equals("")){
            eduTxt.setText( user.getEdu());
            eduTxt.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark) );
        }

        if ( user.getSex() == 1 ){
            sexRG.check(R.id.id_sex_male);
        }

        if ( user.getSex() == 2 ){
            sexRG.check(R.id.id_sex_female);
        }

//        if ( ! user.getDisplayname().equals("") && !user.getBusiness_name().equals("")  &&  ! user.getLocation().equals("") ) {
//            nextbtnRegister.setVisibility(View.GONE);
//        }

        if ( ! user.getDisplayname().equals("") ) {
            name.setText(user.getDisplayname());
            name.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark) );
        }


        if ( ! user.getLocation().equals("") ) {
            addr.setText(user.getLocation());
            addr.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark) );
        }

        if ( ! user.getOccupation().equals("") ) {
            occupation.setText(user.getOccupation_name());
            occupation.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark) );
        }

        if ( ! user.getBusiness().equals("") ) {
            buzz.setText(user.getBusiness_name());
            buzz.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark) );
        }

        if ( ! user.getCategory().equals("") ) {
            categoryTxt.setText(user.getCategory_name());
            categoryTxt.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark) );
        }


        if ( ! user.getDisplayname().equals("") ) {
            intro.setText(user.getIntro());
            intro.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark) );
        }

        if ( ! user.getPhone().equals("") ) {
            phoneTxt.setText(user.getPhone());
            phoneTxt.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark) );
        }

        if ( ! user.getEmail().equals("") ) {
            emailTxt.setText(user.getEmail());
            emailTxt.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark) );
        }

        if ( ! user.getWechat().equals("") ) {
            wechatTxt.setText(user.getWechat());
            wechatTxt.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark) );
        }

        if ( ! user.getOffice().equals("") ) {
            officeTxt.setText(user.getOffice());
            officeTxt.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark) );
        }

        String snail = user.getSnailview();
        if (StringUtil.notNullOrEmpty(snail)) {

            Picasso.with(this)
                    .load(snail)
                    .into(avatar);
        }

        if ( ! user.getIntro().equals("") ) {
            introArea.setVisibility(View.VISIBLE);
            intro.setText(user.getIntro());
            intro.setTextColor(ContextCompat.getColor(AccountActivity.this,R.color.colorPrimaryDark) );
        }


        loading = false;
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra("displayname",user.getDisplayname());
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
